package com.leyou.auth.config;

import com.leyou.auth.utils.RsaUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author huangxin
 * @date 2019/5/11-19:46
 */
@Component
@ConfigurationProperties(prefix = "ly.jwt")
@Data
public class JwtProperties {
    private String secret;
    private String pubKeyPath;
    private String priKeyPath;
    private int expire;
    private String cookieName;

    private PublicKey publicKey;
    private PrivateKey privateKey;

    //类一旦初始化,就应该读取公钥跟私钥
    @PostConstruct
    public void init() throws Exception {
        File pubPath = new File(pubKeyPath);
        File priPath = new File(priKeyPath);

        if (!pubPath.exists() || !priPath.exists()) {
            //如果公钥或私钥不存在,则初始化
            RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
        }

        //读取公钥,私钥
        this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
        this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
    }
}
